package com.springchang.leetcode;


import java.util.Stack;

/**
 * LeetCode 394-字符串解码
 */
public class Solution394 {

    public String decodeString(String s) {
        String decoder = new String();
        Stack<Character> charactorStack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(']' != c) {
                charactorStack.push(c);
            } else {
                String sentence = "";
                while(charactorStack.peek() != '[') {
                    sentence = charactorStack.pop() + sentence;
                }
                charactorStack.pop();
                String count = "";
                while(!charactorStack.isEmpty() && Character.isDigit(charactorStack.peek())) {
                    count = charactorStack.pop() + count;
                }
                //运算结果
                String bigSentence = "";
                for (int j = 0; j < Integer.parseInt(count); j++) {
                    bigSentence += sentence;
                }

                for (int j = 0; j < bigSentence.length(); j++) {
                    charactorStack.push(bigSentence.charAt(j));
                }
            }
        }

        while (!charactorStack.isEmpty()) {
            decoder = charactorStack.pop() + decoder;
        }

        return decoder;
    }

    public static void main(String[] args) {
        Solution394 solution = new Solution394();
        System.out.println(solution.decodeString("3[a2[c]]"));
    }
}
